<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class HuiBuyExport implements FromQuery, WithMapping, WithHeadings
{
    use Exportable;

    protected  $model;

    public function __construct($model)
    {
        $this->model = $model;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function query()
    {

        return $this->model->query()->where(function($query){
            $query->with('member');
            if(request()->keyword)
            {
                $query->whereHas('member',function($query){
                $query->where('nickname','like','%'.request()->keyword.'%')->orWhere('mobile',request()->keyword);
                });
            }
            if(request()->sale_type)
            {
               $query->where('sale_type',request()->sale_type);
            }
            if(request()->status)
            {
               $query->where('status',request()->status);
            }
            if(isset(request()->time[0]) && !empty(request()->time[0])){
                $query->whereBetween('created_at',request()->time);
            }else{
                $query->whereBetween('created_at',[now()->subDays(30)->toDateString(),now()->toDateString()]);
            }
            $query->whereIn('status',[4,5]);
        });
    }

    public function map($invoice): array
    {
        return [
            is_null($invoice->member) ? '--' : $invoice->member->nickname,
            is_null($invoice->member) ? '--' : $invoice->member->mobile,
            $invoice->goods_name,
            $invoice->buy_number,
            $invoice->buy_goods_count_bean,
            $invoice->buy_back_price,
            $invoice->sale_type == 1 ? '金豆' : '现金',
            $invoice->status == 4 ? '申请中' : '已完成',
            $invoice->created_at,
            $invoice->action_at,
        ];
    }

    public function headings(): array
    {
        return [
            '会员昵称',
            '手机号',
            '商品名称',
            '购买次数',
            '金豆(总)',
            '回购价格',
            '出售类型',
            '状态',
            '申请时间',
            '操作时间',
        ];
    }
}
